package dealfunc

import (
	"bufio"
	"net/http"
	"os"
	"github.com/gin-gonic/gin"
)

// 读文件并返回字典
func getAccountData() (map[string]string, error) {
	file, err := os.Open("accountData.txt")
	if err != nil {
		return nil, err
	}
	defer file.Close()

	dataDict := make(map[string]string)
	scanner := bufio.NewScanner(file)

	// 扫描文件
	for scanner.Scan() {
		account := scanner.Text()
		// 下一行
		scanner.Scan()
		password := scanner.Text()
		dataDict[account] = password
	}

	if err := scanner.Err(); err != nil {
		return nil, err
	}

	return dataDict, nil
}

func CheckInf(c *gin.Context) {
	// 账号信息
	var accountData map[string]string

	if err := c.BindJSON(&accountData); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "Invalid request",
		})
		return
	}

	account := accountData["account"]
	password := accountData["password"]

	dataDict, err := getAccountData()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"result": "false",
			"message": "haven't inf",
		})
		return
	}

	// 查找是否有账号
	_, ok := dataDict[account]

	if !ok {
		c.JSON(http.StatusBadRequest, gin.H{
			"result": "false",
			"message": "不存在此账号",
		})
		return
	}

	// 如果密码错误
	if dataDict[account] != password {
		c.JSON(http.StatusBadRequest, gin.H{
			"result": "false",
			"message": "密码错误",
		})
		return
	}

	// 成功
	c.JSON(http.StatusAccepted, gin.H{
		"result": "true",
		"message": "成功",
	})
}